#pragma semicolon 1
#pragma newdecls required

#include <sourcemod>
#include <left4dhooks>

#define PLUGIN_VERSION "1.0"

public Plugin myinfo =
{
	name = "l4d2_StaggersUnlimitedChainsaw",
	author = "X光",
	description = "击退特感女巫无限油电锯",
	version = PLUGIN_VERSION,
	url = "QQ群59046067"
};

public void OnPluginStart()
{
	HookEvent("weapon_fire", Event_WeaponFire);
	HookEvent("player_hurt", Event_PlayerHurt);
}

bool IsValidClient(int client)
{
	return client > 0 && client <= MaxClients && IsClientInGame(client) && GetClientTeam(client) == 2 && IsPlayerAlive(client);
}

bool IsValidInfected(int client)
{
	return client > 0 && client <= MaxClients && IsClientInGame(client) && GetClientTeam(client) == 3 && IsPlayerAlive(client);
}

bool IsValidWitch(int victim)
{
	if (IsValidEntity(victim))
	{
		static char sName[8];
		GetEdictClassname(victim, sName, sizeof sName);
		if (strcmp(sName, "witch") == 0)
			return true;
	}

	return false;
}

public void OnEntityCreated(int entity, const char[] classname)
{
	if (entity <= MaxClients || !IsValidEntity(entity))
		return;

	if (classname[0] != 'w')
		return;

	if (strcmp(classname, "witch") == 0)
		SDKHook(entity, SDKHook_OnTakeDamage, WitchOnTakeDamage);
}

public Action WitchOnTakeDamage(int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &weapon, float damageForce[3], float damagePosition[3])
{
	if (IsValidClient(attacker) && IsValidWitch(victim) && IsValidEntity(weapon))
	{
		char sName[16];
		GetEntityClassname(weapon, sName, sizeof sName);
		if (strcmp(sName, "weapon_chainsaw") == 0)
		{
			SDKHooks_TakeDamage(victim, inflictor, attacker, damage, DMG_BLAST);
			return Plugin_Handled;
		}
	}

	return Plugin_Continue;
}

void Event_WeaponFire(Event event, const char[] name, bool dontBroadcast)
{
	if (event.GetInt("weaponid") == 20)
	{
		int client = GetClientOfUserId(event.GetInt("userid"));
		if (!IsValidClient(client))
			return;

		int weapon = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon");
		if (!IsValidEntity(weapon))
			return;

		char sName[16];
		GetEntityClassname(weapon, sName, sizeof sName);
		if (strcmp(sName, "weapon_chainsaw") == 0)
			SetEntProp(weapon, Prop_Data, "m_iClip1", 30);
	}
}

void Event_PlayerHurt(Event event, const char[] name, bool dontBroadcast)
{
	char sName[16];
	GetEventString(event, "weapon", sName, sizeof sName);
	if (strcmp(sName, "chainsaw") == 0)
	{
		int victim = GetClientOfUserId(event.GetInt("userid"));
		if (IsValidInfected(victim))
		{
			int attacker = GetClientOfUserId(event.GetInt("attacker"));
			if (IsValidClient(attacker))
			{
				L4D_StaggerPlayer(victim, attacker, NULL_VECTOR);
			}
		}
	}
}
